var divContainer = document.getElementById('container');
var imgWidth = 220;// 每张图片的固定宽度

// 1 加入图片元素
function createImgs() {
    for (var i = 0; i <= 40; i++) {
        var img = document.createElement('img');
        img.height = Math.random() * 300 + 200;
        divContainer.appendChild(img);
    }
}

createImgs()

// 2 设置图片的位置
function setPositions() {
    // 计算需要多少列 以及每一列之间的间隙
    function cal() {
        var containerWidth = divContainer.clientWidth;
        var columns = Math.floor(containerWidth / imgWidth);
        var space = (containerWidth - columns * imgWidth) / (columns + 1);
        return {columns, space}
    }
    var info = cal();
    var nextTops = new Array(info.columns).fill(0);
    for (let i = 0; i < divContainer.children.length; i++) {
        var img = divContainer.children[i];
        // 确定img的top
        var minTop = Math.min(...nextTops);
        img.style.top = minTop + "px";
        // 确定img的left
        var index = nextTops.indexOf(minTop);
        img.style.left = (index + 1) * info.space + index * imgWidth + "px";

        // 更新nextTops
        nextTops[index] += img.height + info.space;
    }
    // 确定divContainer的height
    var max = Math.max(...nextTops);
    divContainer.style.height = max + "px";
}

setPositions()

var timer = null;
window.onresize = function () {
    timer && clearTimeout(timer);
    timer = setTimeout(setPositions, 300)
}